<?php
/**
 * Created by PhpStorm.
 * User: shx
 * Date: 2016/11/25
 * Time: 14:49
 */

namespace App\Http\Controllers\Api;

use App\Models\Live\Anchor;
use App\Models\Tag\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AnchorController extends Controller
{
    public function rec($anchor_id)
    {
        $this->checkMaster();

        $anchor = Anchor::findOrFail($anchor_id);

        $tag = Tag::where('anchor_id', $anchor_id)->first();

        if ( ! $tag) $tag = Tag::create(['name' => $anchor->name, 'type' => 'anchor', 'anchor_id' => $anchor_id]);
        if (empty($tag->pinyin)) $tag->autoComputePinyin();

        $tag->is_rec = 1;
        $tag->save();

        return [
            'error' => 0,
            'msg'   => '推荐成功！',
            'id'    => $tag->id
        ];
    }

    public function unrec($tag_id)
    {
        $this->checkMaster();
        $tag = Tag::where('anchor_id', $tag_id)->firstOrFail();

        $tag->update(['is_rec' => 0]);
        return [
            'error' => 0,
            'msg'   => '取消推荐成功！'
        ];
    }

    private function checkMaster()
    {
        if ( session('user') && session('user')->master ) return 0;

        return abort(403);
    }

    public function subscribe($anchor_id) {
        $user = session("user");
        if (!$user) return abort(404);

        DB::table('user_anchor')->where("anchor_id", $anchor_id)->where('user_id', $user->id)->update(['subscribe' => 1]);

        return ['msg' => '开启主播上线微信推送成功！'];
    }

    public function unsubscribe($anchor_id) {
        $user = session("user");
        if (!$user) return abort(404);
        DB::table('user_anchor')->where("anchor_id", $anchor_id)->where('user_id', $user->id)->update(['subscribe' => 0]);

        return ['msg' => '关闭主播上线微信推送成功！'];
    }
}